import React, { useState } from 'react';
import { View, Text, StyleSheet, Image, ScrollView, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { StatusBar } from 'expo-status-bar';
import AppHeader from '../components/AppHeader';
import PrimaryButton from '../components/PrimaryButton';
import UploadField from '../components/UploadField';
import InputField from '../components/InputField';
import { Colors } from '../constants/colors';
import { useNavigation } from '@react-navigation/native';
import { mentorService } from '../services';

export default function InstructorRegisterScreen() {
  const [form, setForm] = useState({
    name: '',
    tel: '',
    credentials: '',
    credentialsFiles: '',
    idCard: '',
    idCardFiles: ''
  });
  const [loading, setLoading] = useState(false);
  const set = (k: keyof typeof form, v: string) => setForm(prev => ({ ...prev, [k]: v }));
  const nav = useNavigation<any>();

  // 验证表单
  const validateForm = () => {
    if (!form.name.trim()) {
      Alert.alert('錯誤', '請輸入導師姓名');
      return false;
    }
    if (!form.tel.trim()) {
      Alert.alert('錯誤', '請輸入手機號碼');
      return false;
    }
    if (!form.credentials.trim()) {
      Alert.alert('錯誤', '請輸入導師資格');
      return false;
    }
    if (!form.credentialsFiles) {
      Alert.alert('錯誤', '請上傳導師資格文件');
      return false;
    }
    if (!form.idCard.trim()) {
      Alert.alert('錯誤', '請輸入身份證號碼');
      return false;
    }
    if (!form.idCardFiles) {
      Alert.alert('錯誤', '請上傳身份證文件');
      return false;
    }
    return true;
  };



  // 处理注册
  const handleRegister = async () => {
    if (!validateForm()) {
      return;
    }

    setLoading(true);
    try {
      const result = await mentorService.addMentor({
        name: form.name.trim(),
        tel: form.tel.trim(),
        credentials: form.credentials.trim(),
        credentialsFiles: form.credentialsFiles,
        idCard: form.idCard.trim(),
        idCardFiles: form.idCardFiles,
        certificateFiles: '', // 设为空字符串，保持API兼容性
      });

      Alert.alert('註冊成功', result.message || '導師註冊申請已提交，請等待審核', [
        {
          text: '確定',
          onPress: () => nav.reset({
            index: 0,
            routes: [{ name: 'MainTabs', params: { initialTab: 'Profile' } }],
          }),
        },
      ]);
    } catch (error: any) {
      console.error('导师注册失败:', error);
      Alert.alert('註冊失敗', error.message || '註冊過程中發生錯誤，請稍後重試');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar style="light" backgroundColor="#f97316" />
      <AppHeader title="導師註冊" showBack variant="plain" />

      <ScrollView style={styles.content} contentContainerStyle={styles.contentInner} showsVerticalScrollIndicator={false}>
        <View style={styles.heroRow}>
          <View>
            <Text style={styles.heroTitle}>成為導師</Text>
            <Text style={styles.heroSub}>管理自己的課程更方便</Text>
          </View>
          <Image source={{ uri: 'https://images.unsplash.com/photo-1599050751795-625cdf5cde0d?q=80&w=200&auto=format&fit=crop' }} style={{ width: 72, height: 72, borderRadius: 36 }} />
        </View>

        <View style={{ marginBottom: 12 }}>
          <InputField
            label="姓名 *"
            value={form.name}
            onChangeText={(v) => set('name', v)}
            placeholder="請輸入導師姓名"
            variant="card"
          />
        </View>

        <View style={{ marginBottom: 12 }}>
          <InputField
            label="手機號碼 *"
            value={form.tel}
            onChangeText={(v) => set('tel', v)}
            placeholder="請輸入手機號碼"
            keyboardType="phone-pad"
            variant="card"
          />
        </View>

        <View style={{ marginBottom: 12 }}>
          <InputField
            label="導師資格 *"
            value={form.credentials}
            onChangeText={(v) => set('credentials', v)}
            placeholder="請輸入導師資格"
            variant="card"
          />
        </View>

        <View style={{ marginBottom: 12 }}>
          <UploadField
            label="導師資格文件 *"
            subtitle="例如:教練證書"
            uri={form.credentialsFiles}
            onUploadComplete={(ossUrl) => set('credentialsFiles', ossUrl)}
            tipText="上傳導師資格證書"
          />
        </View>

        <View style={{ marginBottom: 12 }}>
          <InputField
            label="身份證號碼 *"
            value={form.idCard}
            onChangeText={(v) => set('idCard', v)}
            placeholder="請輸入身份證號碼"
            variant="card"
          />
        </View>

        <View style={{ marginBottom: 12 }}>
          <UploadField
            label="身份證文件 *"
            uri={form.idCardFiles}
            onUploadComplete={(ossUrl) => set('idCardFiles', ossUrl)}
            tipText="上傳身份證照片"
          />
        </View>

        <PrimaryButton
          title={loading ? "註冊中..." : "立即註冊"}
          onPress={handleRegister}
          disabled={loading}
          style={{ marginTop: 12 }}
        />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.white },
  content: { flex: 1 },
  contentInner: { padding: 20, paddingBottom: 40 },

  heroRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 },
  heroTitle: { fontSize: 24, fontWeight: '800', color: Colors.black },
  heroSub: { color: Colors.gray[400], marginTop: 6 },

  card: {
    backgroundColor: Colors.white,
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 14,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: Colors.gray[200],
    shadowColor: Colors.black,
    shadowOpacity: 0.05,
    shadowRadius: 6,
    shadowOffset: { width: 0, height: 2 },
    elevation: 1,
  },

  input: {
    minHeight: 40, // 修复安卓输入框高度问题
    color: Colors.black,
    fontSize: 16,
    textAlignVertical: 'center', // 安卓文本垂直居中
  },
  inputRow: { minHeight: 40 },
  placeholderText: { color: Colors.gray[400] },
});

